package com.yuanfeng.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.activity.dto.*;
import com.yuanfeng.activity.entity.ActivityDiscountBaseEntity;
import com.yuanfeng.activity.entity.ActivityDiscountGoodsEntity;
import com.yuanfeng.activity.feign.BusinessServiceClient;
import com.yuanfeng.activity.feign.GoodsServiceClient;
import com.yuanfeng.activity.mapper.ActivityDiscountBaseMapper;
import com.yuanfeng.activity.mapper.ActivityDiscountGoodsMapper;
import com.yuanfeng.activity.service.ActivityDiscountBaseService;
import com.yuanfeng.activity.vo.*;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.dto.goods.ListPageQueryParamDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ActivityDiscountBaseServiceImpl
 * @Description 限时折扣活动表
 * @Author cyp
 * @Date 2023-05-30 18:05:20
 * @Version 1.0
 **/
@Service
public class ActivityDiscountBaseServiceImpl extends ServiceImpl<ActivityDiscountBaseMapper, ActivityDiscountBaseEntity>
        implements ActivityDiscountBaseService {

    @Resource
    private ActivityDiscountBaseMapper activityDiscountBaseMapper;

    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Autowired
    private GoodsServiceClient goodsServiceClient;

    @Resource
    private ActivityDiscountGoodsMapper activityDiscountGoodsMapper;

    @Override
    public ResponseResult discountCheckLimit(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        String redisKey = YFConfig.YF_USER_TOKEN_USER + param.get("token");
        if (RedisUtil.exists(redisKey)) {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(String.valueOf(param.get("token")));
            String userId = userInfo.getUserId();
            Integer goodsId = (Integer) param.get("goodsId");
            Integer commonId = (Integer) param.get("commonId");
            CheckDiscountLimitVO data = this.baseMapper.queryDiscountInfo(goodsId);
            Integer count = null;
            if(null != data){
                Integer goodsUpperLimit = data.getGoodsUpperLimit();
                Integer discountUpperTime = data.getDiscountUpperTime();
                if( 0 == goodsUpperLimit && 0 == discountUpperTime){
                    rr.setCode(1);
                    rr.setData(null);
                    rr.setMessage("该商品不限购");
                    return rr;
                }
                Calendar cal = Calendar.getInstance();
                Date fdate = new Date();
                cal.setTime(fdate);
                cal.add(Calendar.DATE,-discountUpperTime);
                fdate = cal.getTime();
                param.put("fDate",fdate);
                param.put("goodsId",goodsId);
                param.put("commonId", commonId);
                param.put("userId",userId);
                param.put("discountId",data.getDiscountId());
                count = this.baseMapper.queryOrderGoodsCount(param);
                count = count==null?0:count;
                if(count >= goodsUpperLimit){
                    rr.setCode(2);
                    rr.setData(count);
                    rr.setMessage("该商品已达购买上限,需原价购买");
                }else{
                    rr.setCode(1);
                    rr.setData(count);
                    rr.setMessage("未达上限，可以购买");
                }

            }else{
                rr.setCode(2);
                rr.setMessage("活动未开始或活动已结束，需原价购买");
            }

        }else{
            rr.setCode(3);
            rr.setMessage("token失效，请重新登录");
        }

        return rr;
    }

    @Override
    public ResponseResult queryAllZheKou(ListPageQueryParamDTO param) {
        IPage<Map<String,Object>> page = null;
        try {
            //分页
            //将对象转换为map
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            page = this.baseMapper.queryAllZheKou(new Query<Map<String,Object>>().getPage(data),param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryDiscountBaseList(DiscountBaseListQueryDTO param) {

        DiscountBaseListQueryVO result = new DiscountBaseListQueryVO();

        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            param.setPage((param.getPage() - 1) * param.getLimit());
            List<DiscountBaseListVO> discountBaseList = activityDiscountBaseMapper.selectDiscountBaseList(param);
            Integer totalCount = activityDiscountBaseMapper.selectDiscountBaseListCount(param);
            result.setDiscountBaseList(discountBaseList);
            result.setTotalCount(totalCount);

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

        return ResponseResult.success(result);
    }

    @Override
    @GlobalTransactional
    public ResponseResult addDiscountBase(DiscountBaseAddParamDTO param) {
        // 权限判断
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfoVO != null) {
            String shopId = userInfoVO.getShopId();
            param.setShopId(shopId);
            String shopName = businessServiceClient.selectShopNameByShopId(shopId);
            param.setShopName(shopName);
            param.setUserId(userInfoVO.getUserId());
            param.setUserNickName(userInfoVO.getUserNickname());
            // 暂无用
            param.setDiscountHour(1);
            param.setDiscountCreateTime(new Date());
            Integer commonIsXian = 0;
            Integer discountGoodsState = 0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //预热时间
            if(null == param.getPreStartHour()){
                param.setPreStartHour(0);
            }
            Calendar cal = Calendar.getInstance();
            Date fdate = param.getDiscountStartTime();
            cal.setTime(fdate);
            cal.add(Calendar.HOUR,-param.getPreStartHour());
            fdate = cal.getTime();
            Date currentDate = new Date();
            //有预热
            if(0 != param.getPreStartHour()) {
                param.setPreStartTime(fdate);
                if (currentDate.before(fdate)) {
                    discountGoodsState = 0;
                    param.setDiscountState(0);
                    commonIsXian = 0;
                } else if (DateUtils.belongCalendar(currentDate, fdate, param.getDiscountStartTime()) && 0 != param.getPreStartHour()) {
                    discountGoodsState = 4;
                    param.setDiscountState(4);
                    commonIsXian = 0;
                } else if (DateUtils.belongCalendar(currentDate, param.getDiscountStartTime(), param.getDiscountEndTime())) {
                    discountGoodsState = 1;
                    param.setDiscountState(1);
                    commonIsXian = 3;
                } else {
                    discountGoodsState = 2;
                    param.setDiscountState(2);
                    commonIsXian = 0;
                }
            }else {//没有预热
                if (currentDate.before(param.getDiscountStartTime())) {
                    discountGoodsState = 0;
                    param.setDiscountState(0);
                    commonIsXian = 0;
                } else if (DateUtils.belongCalendar(currentDate, param.getDiscountStartTime(), param.getDiscountEndTime())) {
                    discountGoodsState = 1;
                    param.setDiscountState(1);
                    commonIsXian = 3;
                } else {
                    discountGoodsState = 2;
                    param.setDiscountState(2);
                    commonIsXian = 0;
                }
            }
            DiscountGoodsAddParamDTO goodsAddParam = new DiscountGoodsAddParamDTO();
            if (null == param.getDiscountId()) {
                //插入限时折扣活动表
                activityDiscountBaseMapper.insertDiscountBase(param);
                //插入限时折扣商品表
                goodsAddParam.setDiscountId(param.getDiscountId());
                goodsAddParam.setDiscountGoodsList(param.getDiscountGoodsList());
                goodsAddParam.setToken(param.getToken());
                addDiscountGoods(goodsAddParam);
                return ResponseResult.success(param.getDiscountId());
            } else {
                CommonIsXianUpdateDTO commonIsXianUpdateParam = new CommonIsXianUpdateDTO();
                activityDiscountBaseMapper.updateDiscountBase(param);
                // 查询参与此限时折扣的商品
                List<Integer> commonList = activityDiscountGoodsMapper.selectDiscountGoods(param.getDiscountId());
                // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣
                commonIsXianUpdateParam.setCommonIdList(commonList);
                commonIsXianUpdateParam.setCommonIsXian(0);

                if (!CollectionUtils.isEmpty(commonList) && commonList.size() > 0) {
                    activityDiscountBaseMapper.updateCommonIsXian3(commonIsXianUpdateParam);
                }
                activityDiscountGoodsMapper.deleteDiscountGoods(param.getDiscountId());
                //插入限时折扣商品表
                goodsAddParam.setDiscountId(param.getDiscountId());
                goodsAddParam.setDiscountGoodsList(param.getDiscountGoodsList());
                goodsAddParam.setToken(param.getToken());
                addDiscountGoods(goodsAddParam);
            }

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryFinishBaseList(FinishBaseListQueryDTO param) {
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<Map<String,Object>> baseList = activityDiscountBaseMapper.selectFinishBaseList(new Query<>().getPage(map),param);
        return ResponseResult.success(PageUtils.getPage(baseList));
    }

    @Override
    public ResponseResult deletePlatforDiscountBase(DiscountBaseListQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            this.baseMapper.deleteById(param.getDiscountId());
            activityDiscountGoodsMapper.delete(new LambdaQueryWrapper<ActivityDiscountGoodsEntity>()
                                       .eq(ActivityDiscountGoodsEntity::getDiscountId,param.getDiscountId()));
            return ResponseResult.success(BizCodeEnume.DELETE_SUCCESS);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryPlatforDiscountBaseDetail(DiscountBaseListQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            try {
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<ActivityDiscountGoodsEntity> page = activityDiscountGoodsMapper.selectPage(new Query<ActivityDiscountGoodsEntity>().getPage(data), new LambdaQueryWrapper<ActivityDiscountGoodsEntity>().eq(null!=param.getDiscountId(),ActivityDiscountGoodsEntity::getDiscountId,param.getDiscountId()));

                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryPlatformDiscountBaseList(DiscountBaseListQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            try {
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<DiscountBaseListVO> page = this.baseMapper.queryPlatformDiscountBaseList(new Query<DiscountBaseListVO>().getPage(data), param);

                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryDiscountBaseCopy(Map<String, Object> param) {
        DiscountBaseDetailVO discountBase = this.baseMapper.selectDiscountBaseDetail(Integer.valueOf(param.get("discountId").toString()));

        IPage<DiscountGoodsListVO> page=this.baseMapper.selectDiscountGoodsDetail(new Query<DiscountGoodsListVO>().getPage(param),
                param);


        if (page != null && page.getRecords().size()>0){
            for (DiscountGoodsListVO goodsListResult : page.getRecords()) {
                goodsListResult.setDiscountGoodsId(null);
                goodsListResult.setDiscountId(null);
            }
        }

        discountBase.setDiscountGoodsList(page.getRecords());
        discountBase.setDiscountGoodsListCount((int) page.getTotal());
        discountBase.setDiscountId(null);

        return ResponseResult.success(discountBase);
    }
    // 添加折扣商品
    public ResponseResult addDiscountGoods(DiscountGoodsAddParamDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            List<DiscountGoodsListDTO> discountGoodsList = param.getDiscountGoodsList();
            String shopId = userPermissionsResult.getShopId();

            // 查询店铺活动详情
            DiscountBaseDetailResultVO discountBase = activityDiscountBaseMapper
                    .selectDiscountBaseDetail2(param.getDiscountId());

            Integer commonId = null;

            // 校验商品是否存在或重复
            if (CollectionUtils.isEmpty(discountGoodsList)) {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), "无效必传参数：" + JSON.toJSONString(param));
            }

            Integer commonId2 = discountGoodsList.get(0).getCommonId();
            Integer flag = activityDiscountGoodsMapper.checkSpecNum(commonId2);
            if (flag.equals(1)) {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.SPEC_REPEAT.getMsg()+JSON.toJSONString(param));
            }

            for (DiscountGoodsListDTO discountGoods : discountGoodsList) {
                commonId = discountGoods.getCommonId();

                DiscountGoodsAddParamDTO addGoods = new DiscountGoodsAddParamDTO();
                addGoods.setDiscountId(param.getDiscountId());

                addGoods.setDiscountName(discountBase.getDiscountName());
                addGoods.setDiscountTitle(discountBase.getDiscountTitle());
                addGoods.setDiscountExplain(discountBase.getDiscountExplain());
                addGoods.setGoodsStartTime(discountBase.getDiscountStartTime());
                addGoods.setGoodsEndTime(discountBase.getDiscountEndTime());
                addGoods.setGoodsUpperLimit(discountBase.getDiscountUpperLimit());
                addGoods.setGoodsLowerLimit(discountBase.getDiscountLowerLimit());
                addGoods.setDiscountGoodsState(discountBase.getDiscountState());

                addGoods.setDiscountUpperTime(discountBase.getDiscountUpperTime());
                addGoods.setPreStartHour(discountBase.getPreStartHour());
                if(null != discountBase.getPreStartHour() && 0 != discountBase.getPreStartHour()){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Calendar cal = Calendar.getInstance();
                    Date fdate = discountBase.getDiscountStartTime();
                    cal.setTime(fdate);
                    cal.add(Calendar.HOUR,-discountBase.getPreStartHour());
                    fdate = cal.getTime();
                    addGoods.setPreStartTime(fdate);
                }
                addGoods.setDiscountGoodsRecommend(0);
                addGoods.setGoodsBuyCount(0);

                addGoods.setGoodsId(discountGoods.getGoodsId());
                addGoods.setGoodsName(discountGoods.getGoodsName());
                addGoods.setGoodsImage(discountGoods.getGoodsImage());
                addGoods.setGoodsPrice(discountGoods.getGoodsPrice());
                addGoods.setDiscountPrice(discountGoods.getDiscountPrice());
                addGoods.setCommonId(commonId);
                addGoods.setShopId(shopId);
                addGoods.setDiscountAmount(discountGoods.getDiscountAmount());

                if (null == param.getDiscountGoodsId()) {
                    activityDiscountGoodsMapper.insertDiscountGoods(addGoods);
                } else {
                    activityDiscountGoodsMapper.updateDiscountGoods(addGoods);
                }
                // 更新显示折扣字段//商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣',

                if (null != commonId) {
                    Integer commonIsXian = 3;
                    Map<String,Object> param2 = new HashMap<>();
                    param2.put("commonIsXian",commonIsXian);
                    param2.put("commonId",commonId);
                    goodsServiceClient.updateCommonIsXian(param2);
                }
            }
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryDiscountBaseDetail(DiscountBaseDetailQueryDTO param) throws IllegalAccessException {

        DiscountBaseDetailVO discountBase = activityDiscountBaseMapper.selectDiscountBaseDetail(param.getDiscountId());
        Map data= ParseMapUtils.beanToMap(param);
        IPage<DiscountGoodsListVO> page=activityDiscountGoodsMapper.selectDiscountGoodsDetail(new Query<DiscountGoodsListVO>().getPage(data),
                param);

        discountBase.setDiscountGoodsList(page.getRecords());
        discountBase.setDiscountGoodsListCount((int) page.getTotal());

        return ResponseResult.success(discountBase);
    }

}
